<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2022-2099 李志刚（854378082@qq.com）
 * @Date: 2021-02-26 11:02:29
 * @Description: 通用无限级分类
 * @LastEditors: 李志刚
 * @LastEditTime: 2022-04-21 16:35:19
 * @FilePath: /CoinCMF/app/Http/Controllers/Console/Common/TypeController.php
 */

namespace App\Http\Controllers\Console\Common;

use App\Models\Common\Type;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Requests\Cms\TypeRequest;
use App\Http\Requests\Cms\TypeUpdateRequest;
use App\Http\Requests\DetailRequest;
use App\Http\Requests\SortRequest;

class TypeController extends Controller
{
    public function getList()
    {
        $all = Type::select('id', 'parent_id', 'name', 'sort')->orderBy('sort', 'asc')->orderBy('id', 'asc')->get();
        $tree = $this->toTree($all, '0');
        return $this->resJson(200, '成功', $tree);
    }
    private function toTree($data, $pid)
    {
        $tree = [];
        if ($data->count() > 0) {
            foreach ($data as $v) {
                if ($v->parent_id == $pid) {
                    $v = ['type_id' => $v->id, 'name' => $v->name, 'sort' => $v->sort, '_showChildren' => true];
                    $v['children'] = $this->toTree($data, $v['type_id']);
                    $tree[] = $v;
                }
            }
        }
        return $tree;
    }
    public function getDetail(DetailRequest $request)
    {
        $detail_id = $request->input('detail_id');
        $detail = Type::select('id', 'parent_id', 'name', 'sort')->findOrFail($detail_id);
        return $this->resJson(200, '成功', $detail);
    }
    public function postCreate(TypeRequest $request)
    {
        $data = $request->input();
        Type::create(['parent_id' => $data['parent_id'], 'name' => $data['name'], 'sort' => $data['sort']]);
        return $this->resJson(200, '成功');
    }
    public function postEdit(TypeUpdateRequest $request)
    {
        $data = $request->input();
        Type::where('id', $data['detail_id'])->update(['name' => $data['name'], 'sort' => $data['sort']]);
        return $this->resJson(200, '成功');
    }
    public function postSort(SortRequest $request)
    {
        Type::where('id', $request->input('detail_id'))->update(['sort' => $request->input('sort')]);
        return $this->resJson(200, '成功');
    }
    public function postRemove(DetailRequest $request)
    {
        $detail_id = $request->input('detail_id');
        DB::transaction(function() use($detail_id){
            // 先找出所有子分类
            $arr = DB::select("SELECT t2.id as id FROM (SELECT @r AS _ids, (SELECT @r := GROUP_CONCAT(id) FROM cms_type WHERE FIND_IN_SET(parent_id,@r)) AS id FROM (SELECT @r := ".$detail_id.") vars NATURAL JOIN cms_type h WHERE @r IS NOT NULL) t1,cms_type t2 WHERE FIND_IN_SET(t2.id,t1._ids)");
            $ids = array_map(function($q){
                return $q->id;
            },$arr);
            Type::whereIn('id',$ids)->delete();
        });
        return $this->resJson(200, '成功');
    }
}
